import web
import simplejson
from models_webpy import *


class Groups:

    def GET(self):

        dataset = Group().getAllByCurrentUser()

        if dataset:
            results = dataset
        else:
            results = {}

        return simplejson.dumps(results)


class New:

    def POST(self):
        data = web.input()
        result = Group().create(data.name)

        return simplejson.dumps(result)


class Update:

    def POST(self):
        data = web.input()

        result = None
        g = Group().getById(int(data.id))
        if g:
            if 'name' in data:
                g.update(name=data.name)
                result = web.net.websafe(data.name)

            elif 'description' in data:
                g.update(description=data.description)
                result = web.net.websafe(data.description)

        return result


class Delete:
    def GET(self, id):
        if id.isdigit():
            g = Group().getById(int(id))
            if g:
                hosts = Host().getAllByGroupId(int(id))
                for h in hosts:
                    h.delete()
                g.delete()
